SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.[DnnProduct_CDS_CreateRedemptionCodes]
	@RequestID int
AS
BEGIN
	SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
	BEGIN TRANSACTION;

	DECLARE @RedemptionCodes int;
	
	SELECT @RedemptionCodes = CodesRequested
	FROM dbo.[DnnProduct_CDS_Requests]
	WHERE ID = @RequestID;

	IF (@RedemptionCodes > 0) BEGIN	
		BEGIN TRY
			INSERT INTO dbo.[DnnProduct_CDS_RedemptionCodes] (RedemptionCode, RequestID)
			SELECT TOP (@RedemptionCodes) Code, @RequestID
			FROM dbo.[DnnProduct_CDS_RedemptionCodesAvailable];
			
			DELETE TOP(@RedemptionCodes)
			FROM dbo.[DnnProduct_CDS_RedemptionCodesAvailable];
		END TRY
		BEGIN CATCH
			IF @@TRANCOUNT > 0
				ROLLBACK TRANSACTION;
		END CATCH;
	END;

	IF @@TRANCOUNT > 0
	    COMMIT TRANSACTION;

	SELECT RedemptionCode
	FROM dbo.[DnnProduct_CDS_RedemptionCodes]
	WHERE RequestID = @RequestID
END
GO
